package ui;

import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JFrame;

public class Mp3Player extends JFrame {

	// Constructor
	public Mp3Player() {

		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("Test Sound Clip");
		this.setSize(300, 200);
		this.setVisible(true);

		URL url = this.getClass().getResource("/mp3/audio/test.mp3");

		try {
			AudioInputStream in = AudioSystem.getAudioInputStream(url);

			AudioInputStream din = null;
			if (in != null) {
				AudioFormat baseFormat = in.getFormat();

				AudioFormat decodedFormat = new AudioFormat(
						AudioFormat.Encoding.PCM_SIGNED,
						baseFormat.getSampleRate(), 16,
						baseFormat.getChannels(), baseFormat.getChannels() * 2,
						baseFormat.getSampleRate(), false);

				din = AudioSystem.getAudioInputStream(decodedFormat, in);
				
				//bytes = seconds * sample rate * frame size
				
				
				
				//long second = (long)(300000 * baseFormat.getSampleRate() * baseFormat.getChannels() * 2);
				//System.out.println(din.markSupported());
				//din.skip(second);
			


				byte[] data = new byte[4096];


				DataLine.Info info = new DataLine.Info(Clip.class,
						decodedFormat);
//				SourceDataLine line = (SourceDataLine) AudioSystem
//						.getLine(info);
				
				Clip clip = (Clip)AudioSystem.getLine(info);
				
				clip.open(din);
				
				
			
			
				clip.start();
			
				
				
//				line.open(decodedFormat);

//				if (line != null) {
//					// Start
//					line.start();
//					int nBytesRead = 0;
//
//					while (nBytesRead != -1) {
//						nBytesRead = din.read(data, 0, data.length);
//						if (nBytesRead != -1)
//							line.write(data, 0, nBytesRead);
//					}
//					// Stop
//					line.drain();
//					line.stop();
//					line.close();
				
					clip.close();
				
					din.close();
	//			}

				in.close();
			}

		} catch (UnsupportedAudioFileException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void main(String[] args) {

		new Mp3Player();

	}

}
